package com.sebklebes.radar.gae.service.impl;

import com.beoui.geocell.GeocellManager;
import com.sebklebes.radar.gae.dao.RadarDAO;
import com.sebklebes.radar.gae.entity.RadarEntity;
import com.sebklebes.radar.gae.service.RadarService;

import java.util.List;
import java.util.logging.Logger;

/**
 * User:  catalin.besleaga
 * Date: 5/16/11
 * Time: 10:42 PM
 */

public class RadarServiceImpl implements RadarService {

	private static final Logger log = Logger.getLogger(RadarServiceImpl.class.getName());
	private RadarDAO radarDAO;

	private static final double rangeInMeters = 500;
	private static final int maxNumberOfResults = 10;

	public RadarDAO getRadarDAO() {
		return radarDAO;
	}

	public void setRadarDAO(RadarDAO radarDAO) {
		this.radarDAO = radarDAO;
	}

	public RadarEntity createOrUpdate(RadarEntity radarEntity) {
		log.info("createOrUpdate, radarEntity = " + radarEntity);

		if (radarEntity.getKey() == null || "".equals(radarEntity.getKey().toString())) {
			// create a new radar if there is no radar in a range of rangeInMeters m
			List<RadarEntity> radarEntities = radarDAO.getRadars(radarEntity.getLatitude(), radarEntity.getLongitude(), rangeInMeters, maxNumberOfResults);

			if (radarEntities.size() == 0) {
				List<String> geocells = GeocellManager.generateGeoCell(radarEntity.getLocation());
				radarEntity.setGeocells(geocells);
				return radarDAO.createObject(radarEntity);
			} else {
				// get the first radar in the retrieved list (most probably the only one, since we won't save more than 1 radar in a 500m range)
				RadarEntity firstRadar = radarEntities.get(0);
				firstRadar.setLastUpdate(radarEntity.getLastUpdate());
				firstRadar.setNumberOfHits(firstRadar.getNumberOfHits() + 1);
				return radarDAO.updateObject(firstRadar);
			}
		} else {
			radarDAO.updateObject(radarEntity);
			RadarEntity r = radarDAO.findObjectById(radarEntity.getKey());
			return r;
		}
	}

	public List<RadarEntity> getRadars(Double latitude, Double longitude, Double range, Double maxNumerOfResults) {
		return radarDAO.getRadars(latitude, longitude, range, maxNumberOfResults);
	}
}
